package com.itheima;

import com.alibaba.fastjson.JSON;
import com.itheima.Service.SkuService;
import com.itheima.api.Sku;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/ww")
public class Test {

    @Autowired
    private SkuService skuService;

    //1. 数据导入到数据库
    //2. 把数据库数据通过查询数据
    //3. 建立索引库和mapping映射
    //   参考：sku需要加入到索引库的字段
    //4. 把数据插入到ES索引库（批量）
    //5. 查询结果9w+

    @GetMapping("/test")
    public String Tate() throws IOException {
        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost("localhost", 9200, "http"));

        RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);

        List<Sku> list = skuService.list();
        System.out.println("list = " + list);
        BulkRequest bulkRequest = new BulkRequest();
        for (Sku sku : list) {
            bulkRequest.add(new IndexRequest("user_sh")
                    .id(sku.getId())
                    .source(JSON.toJSONString(sku), XContentType.JSON)
            );


        }


        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.status());
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bulk.status().toString();


    }


}